from importlib import import_module
from flask import Blueprint

def path(rule,view_func):
    # 把蓝图下视图和路由之间的映射关系处理成字典结构，方便后面注册蓝图的时候，直接传参
    return {"rule":rule,"view_func":view_func}

def include(url_prefix, blueprint_path):
    """把路由前缀和蓝图进行关系映射"""
    return {"url_prefix":url_prefix,"blueprint_path":blueprint_path}

def api(name,method):
    """把api接口访问别名和视图进行关系映射"""
    return {"name":name,"method":method}

def init_blueprint(app):
    """自动注册蓝图"""
    # 读取蓝图列表
    blueprint_path_list = app.config.get("INSTALLED_APPS")
    # 读取总路由文件
    url_path = app.config.get("URL_PATH")
    urlpatterns = import_module(url_path).urlpatterns  # 加载蓝图下的子路由文件

    for blueprint_path in blueprint_path_list:
        blueprint_name = blueprint_path.split(".")[-1]
        # 自动创建蓝图对象
        blueprint = Blueprint(blueprint_name, blueprint_path)

        url_module = import_module("%s.urls" % blueprint_path)
        #注册路由和视图
        try:
            for urls in url_module.urlpatterns:
                blueprint.add_url_rule(**urls)
        except:
            pass

        #注册rpc接口
        try:
            for api in url_module.jsonpatterns:
                app.jsonrpc.site.register(blueprint_name.title()+"."+api["name"],api["method"])
        except:
            pass

        # 添加蓝图的路由前缀
        url_prefix = ""  # 蓝图路由前缀
        for urlpattern in urlpatterns:
            if urlpattern["blueprint_path"] == blueprint_name+".urls":
                url_prefix = urlpattern["url_prefix"]
                break

        # 注册蓝图对象到app应用对象中
        app.register_blueprint(blueprint, url_prefix=url_prefix)

        try:
            # 注册蓝图下的模型
            import_module(blueprint_path + ".models")
            # 注册蓝图下的后台站点配置
            import_module(blueprint_path+".admin")
        except:
            pass

        # 后台站点首页相关初始化
        from application import admin, AdminIndexView
        admin._set_admin_index_view(index_view=AdminIndexView(
            name=app.config["ADMIN_HOME_NAME"],
            template=app.config["ADMIN_HOME_TEMPLATE"],
        ))